package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class AutoChannelsHandler implements MsgHandler {
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("接收补货成功");
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if(supplyContract==null)return;
        VmVO vmVO = vmService.getVMInfo(supplyContract.getInnerCode());
        if(vmVO==null)return;
        int userId = taskService.getLeastUser(vmVO.getRegionId(), false);
        if(userId==0)return;
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setUserId(userId);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setCreateType(0);
        taskViewModel.setAssignorId(0);
        taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(
                s->{
                    TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
                    taskDetailsViewModel.setChannelCode(s.getChannelId());
                    System.out.println(s.getChannelId());
                    taskDetailsViewModel.setSkuId(s.getSkuId());
                    taskDetailsViewModel.setSkuImage(s.getSkuImage());
                    taskDetailsViewModel.setSkuName(s.getSkuName());
                    taskDetailsViewModel.setExpectCapacity(s.getCapacity());
                    return taskDetailsViewModel;
                }
        ).collect(Collectors.toList()));
        taskService.createTask(taskViewModel);
    }
}
